import logging as logger
from fastapi import HTTPException
from pydantic import ValidationError
from sqlalchemy.testing.config import db
from sqlmodel import select
from api.deps import SessionDep
from schemas.driver_schema import DriverCreate
from models.driver_model import Driver
from .exception import SQLException
async def create_driver(*,session:SessionDep,driver:DriverCreate):
    "创建司机"
    new_driver = None
    default = {"full_name":" ".join([driver.first_name,driver.last_name])}
    try:
        new_driver = Driver.model_validate(driver,update=default)
        session.add(new_driver)
        await session.commit()
        await session.refresh(new_driver)
        logger.debug(f"创建司机成功：{new_driver}")
        return new_driver
    except (ValidationError,SQLException,Exception) as e:
        logger.error(e)
        raise e
async def find_driver_license_plate(*,session:SessionDep,license_plate:str):
    "通过司机车牌号查询司机信息"
    stmt = select(Driver).where(Driver.license_plate==license_plate)
    result = await session.exec(stmt)
    db_driver = result.first()
    if db_driver is None:
        raise HTTPException(404,"司机不存在")
    else:
        await session.refresh(db_driver)
    return db_driver